package com.higold.cloud.utils

import android.annotation.SuppressLint
import android.app.ActivityManager
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import android.view.View
import java.security.MessageDigest
import android.view.ViewTreeObserver
import com.higold.cloud.R.id.all
import java.math.BigDecimal
import java.text.DecimalFormat
import android.R.attr.data
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Log
import java.io.File
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*


/**
 * Created by xuhao on 2017/12/6.
 * desc: APP 相关的工具类
 */

class AppUtils private constructor() {


    init {
        throw Error("Do not need instantiate!")
    }

    companion object {

        private val DEBUG = true
        private val TAG = "AppUtils"


        /**
         * 得到软件版本号
         *
         * @param context 上下文
         * @return 当前版本Code
         */
        fun getVerCode(context: Context): Int {
            var verCode = -1
            try {
                val packageName = context.packageName
                verCode = context.packageManager
                        .getPackageInfo(packageName, 0).versionCode
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }

            return verCode
        }


        /**
         * 获取应用运行的最大内存
         *
         * @return 最大内存
         */
        val maxMemory: Long
            get() = Runtime.getRuntime().maxMemory() / 1024


        /**
         * 得到软件显示版本信息
         *
         * @param context 上下文
         * @return 当前版本信息
         */
        fun getVerName(context: Context): String {
            var verName = ""
            try {
                val packageName = context.packageName
                verName = context.packageManager
                        .getPackageInfo(packageName, 0).versionName
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
            }

            return verName
        }


        @SuppressLint("PackageManagerGetSignatures")
                /**
                 * 获取应用签名
                 *
                 * @param context 上下文
                 * @param pkgName 包名
                 * @return 返回应用的签名
                 */
        fun getSign(context: Context, pkgName: String): String? {
            return try {
                @SuppressLint("PackageManagerGetSignatures") val pis = context.packageManager
                        .getPackageInfo(pkgName,
                                PackageManager.GET_SIGNATURES)
                hexDigest(pis.signatures[0].toByteArray())
            } catch (e: PackageManager.NameNotFoundException) {
                e.printStackTrace()
                null
            }

        }

        /**
         * 将签名字符串转换成需要的32位签名
         *
         * @param paramArrayOfByte 签名byte数组
         * @return 32位签名字符串
         */
        private fun hexDigest(paramArrayOfByte: ByteArray): String {
            val hexDigits = charArrayOf(48.toChar(), 49.toChar(), 50.toChar(), 51.toChar(), 52.toChar(), 53.toChar(), 54.toChar(), 55.toChar(), 56.toChar(), 57.toChar(), 97.toChar(), 98.toChar(), 99.toChar(), 100.toChar(), 101.toChar(), 102.toChar())
            try {
                val localMessageDigest = MessageDigest.getInstance("MD5")
                localMessageDigest.update(paramArrayOfByte)
                val arrayOfByte = localMessageDigest.digest()
                val arrayOfChar = CharArray(32)
                var i = 0
                var j = 0
                while (true) {
                    if (i >= 16) {
                        return String(arrayOfChar)
                    }
                    val k = arrayOfByte[i].toInt()
                    arrayOfChar[j] = hexDigits[0xF and k.ushr(4)]
                    arrayOfChar[++j] = hexDigits[k and 0xF]
                    i++
                    j++
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }

            return ""
        }


        /**
         * 获取设备的可用内存大小
         *
         * @param context 应用上下文对象context
         * @return 当前内存大小
         */
        fun getDeviceUsableMemory(context: Context): Int {
            val am = context.getSystemService(
                    Context.ACTIVITY_SERVICE) as ActivityManager
            val mi = ActivityManager.MemoryInfo()
            am.getMemoryInfo(mi)
            // 返回当前系统的可用内存
            return (mi.availMem / (1024 * 1024)).toInt()
        }


        fun getMobileModel(): String {
            var model: String? = Build.MODEL
            model = model?.trim { it <= ' ' } ?: ""
            return model
        }

        /**
         * 获取控件宽度
         * */
        fun ViewWidth(view: View): Int {
            var w = -1
            val vto = view.viewTreeObserver
            vto.addOnPreDrawListener {
                w = view.measuredWidth
                true
            }
            return w
        }

        /**
         * 获取手机系统SDK版本
         *
         * @return 如API 17 则返回 17
         */
        val sdkVersion: Int
            get() = android.os.Build.VERSION.SDK_INT


        /**
         * @param path 文件夹路径
         */
        fun isExist(path: String) {
            val file = File(path)
            //判断文件夹是否存在,如果不存在则创建文件夹
            if (!file.exists()) {
                file.mkdir()
                Log.e("创建了", path)
            }
        }


        fun changeFloatToString(double: Double): String {
            val decimalFormat = DecimalFormat("##.##")
            return decimalFormat.format(double)
        }

        fun compressImage(filePath: String, targetPath: String?, quality: Int): String {
            val bm = getSmallBitmap(filePath)//获取一定尺寸的图片
            if (targetPath != null)
                isExist(targetPath)
            val outputFile = File(targetPath!!)
            try {
                if (!outputFile.exists()) {
                    outputFile.parentFile.mkdirs()
                } else {
                    outputFile.delete()
                }
                val out = FileOutputStream(outputFile)
                bm.compress(Bitmap.CompressFormat.JPEG, quality, out)
            } catch (e: Exception) {

            }

            return outputFile.path
        }

        /**
         * 根据路径获得图片信息并按比例压缩，返回bitmap
         */
        fun getSmallBitmap(filePath: String): Bitmap {
            val options = BitmapFactory.Options()
            options.inJustDecodeBounds = true//只解析图片边沿，获取宽高
            BitmapFactory.decodeFile(filePath, options)
            // 计算缩放比
            options.inSampleSize = calculateInSampleSize(options, 480, 800)
            // 完整解析图片返回bitmap
            options.inJustDecodeBounds = false
            return BitmapFactory.decodeFile(filePath, options)
        }

        fun calculateInSampleSize(options: BitmapFactory.Options,
                                  reqWidth: Int, reqHeight: Int): Int {
            val height = options.outHeight
            val width = options.outWidth
            var inSampleSize = 1
            if (height > reqHeight || width > reqWidth) {
                val heightRatio = Math.round(height.toFloat() / reqHeight.toFloat())
                val widthRatio = Math.round(width.toFloat() / reqWidth.toFloat())
                inSampleSize = if (heightRatio < widthRatio) heightRatio else widthRatio
            }
            return inSampleSize
        }

        fun decodeUriAsBitmap(context: Context, uri: Uri): Bitmap? {
            var bitmap: Bitmap? = null
            try {
                // 先通过getContentResolver方法获得一个ContentResolver实例，
                // 调用openInputStream(Uri)方法获得uri关联的数据流stream
                // 把上一步获得的数据流解析成为bitmap
                bitmap = BitmapFactory.decodeStream(context.contentResolver.openInputStream(uri))
            } catch (e: FileNotFoundException) {
                e.printStackTrace()
                return null
            }

            return bitmap
        }

        fun saveBitmap(bitmap: Bitmap, path: String) {
            val f = File(path)
            if (f.exists()) {
                f.delete()
            }
            try {
                val out = FileOutputStream(f)
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, out)
                out.flush()
                out.close()
            } catch (e: FileNotFoundException) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            } catch (e: IOException) {
                // TODO Auto-generated catch block
                e.printStackTrace()
            }

        }

        /**
         *
         * @param time  1541569323155
         * @param pattern yyyy-MM-dd HH:mm:ss
         * @return 2018-11-07 13:42:03
         */
        fun getDateString(time: Long, pattern: String): String {
            val date = Date(time)
            val format = SimpleDateFormat(pattern, Locale.getDefault())
            return format.format(date)
        }
    }


}